//缓冲区类

#ifndef M_BUFFER_H_
#define M_BUFFER_H_


#include<vector>
#include<algorithm>
#include<cassert>
using namespace std;

namespace bitlog{

    #define BUFFER_DEFAULT_SIZE (1*1024*1024)
    #define BUFFER_INCREMENT_SIZE (1*1024*1024)
    #define BUFFER_THRESHOLD_SIZE (10*1024*1024)
    class Buffer{
        public:
            Buffer()
            :_reader_idx(0),_writer_idx(0),_buffer(BUFFER_DEFAULT_SIZE) {}
            bool empty() {return _reader_idx==_writer_idx;}
            //返回可读数据的长度
            size_t readAbleSize() {return _writer_idx-_reader_idx;}
            size_t writeAbleSize() {return _buffer.size()-_writer_idx;}
            //重置读写位置，初始化缓冲区
            void reset() {_writer_idx=_reader_idx=0;}
            //对Buffer进行交换操作
            void swap(Buffer& buffer){
                _buffer.swap(buffer._buffer);
                std::swap(_reader_idx, buffer._reader_idx);
                std::swap(_writer_idx, buffer._writer_idx);
            }
            //向缓冲区写入数据
            void push(const char* data,size_t len){
                assert(len<writeAbleSize());
                ensureEnoughSpace(len);
                std::copy(data,data+len,&_buffer[_writer_idx]);
                _writer_idx+=len;
            }
            //返回可读数据的起始地址
            const char* begin(){
                return &_buffer[_reader_idx];
            }
            void pop(size_t len){
                _reader_idx+=len;
                assert(_reader_idx<=_writer_idx);
            }
        protected:
            void ensureEnoughSpace(size_t len){
                if(writeAbleSize()>=len) return;
                size_t newcapacity;
                if(_buffer.size()<BUFFER_THRESHOLD_SIZE){
                    newcapacity=_buffer.size()*2+len;
                }else{
                    newcapacity=_buffer.size()+BUFFER_INCREMENT_SIZE+len;
                }
                _buffer.resize(newcapacity);
            }
        private:
            vector<char> _buffer;
            size_t _reader_idx; //当前可读数据的指针--本质是下标
            size_t _writer_idx; //当前可写数据的指针
    };
}

#endif